#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "commd.hpp"
#include "Log.hpp"
#include "InitAddr.hpp"
using namespace std;
const int ReConnect = 5;


bool Connect(const string& serverip, uint16_t serverport, int* cnt) {
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        lg.LogMessage(Fatal, "create socket error, error code: %d, erorr string: %s", errno, strerror(errno));
        return false;
    }

    // 创建套接字成功
    lg.LogMessage(Debug, "create socket success, sockfd: %d", sockfd);
    // 填充服务端网路信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    // server.sin_addr.s_addr = inet_addr(serverip.c_str());
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    // 建立连接
    int res = connect(sockfd, (struct sockaddr*)&server, sizeof server);
    if (res == 0) {
        // 如果连接成功过，cnt直接清0
        *cnt = 0;
        string send_message;
        while (true) {
            cout << "Please Enter# ";
            getline(cin, send_message);
            if (send_message == "quit") {
                return true;
            }

            // 发送
            res = write(sockfd, send_message.c_str(), send_message.size());
            if (res > 0) {
                // 接收服务器回响
                char buffer[1024];
                res = read(sockfd, buffer, sizeof(buffer) - 1);
                if (res > 0) {
                    buffer[res] = '\0';
                    cout << "server echo# " << buffer << endl;
                } else if (res == 0) {
                    // 读到0，说明对端关闭了
                    close(sockfd);
                    return true;
                } else {
                    // 读失败
                    return false;
                }
            } else {
                // 写失败
                close(sockfd);
                return false;
            }

        }
    } else {
        // 连接失败
        close(sockfd);
        return false;
    }
    close(sockfd);
    *cnt = 0;
    return true;
}

int main(int argc, char* args[]) {
    if (argc != 3) {
        cout << "Usage:\n\r" << args[0] << ", server_ip server_port\n" << endl;
        return 0;
    }
    string serverip = args[1];
    uint16_t serverport = stoi(args[2]);
    int cnt = 0;
    while (cnt < ReConnect) {
        bool res = Connect(serverip, serverport, &cnt);
        if (res) {
            break;
        } else {
            sleep(1);
            cout << "server offline, retrying……, count: " << cnt + 1 << endl;
            cnt++;
        }
    }
    

    if (cnt >= ReConnect) {
        cout << "server offline……" << endl;
    }

}